package com.ysweet.web.controller;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.ysweet.web.core.interceptor.AuthCheck;
import com.ysweet.common.core.controller.BaseController;
import com.ysweet.common.core.domain.AjaxResult;
import com.ysweet.shop.domain.YsUser;
import com.ysweet.shop.domain.dto.LoginParam;
import com.ysweet.shop.service.IYsUserService;
import com.ysweet.web.core.service.AuthService;
import com.ysweet.web.core.service.JwtToken;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.LinkedHashMap;
import java.util.Map;

/***
 *登录登出相关逻辑
 * @author 小金木
 * @date 2021年5月31日09:06:49
 */
@Api(value = "登录登出相关逻辑", tags = {"登录登出相关逻辑"})
@RestController
@RequestMapping("/wxapp")
@RequiredArgsConstructor
public class LoginController extends BaseController {

	private final AuthService authService;

	private final IYsUserService ysUserService;

	/**
	 * 小程序登陆接口
	 */
	@PostMapping("/token")
	@ApiOperation(value = "小程序登陆", notes = "小程序登陆")
	public AjaxResult<Map<String, Object>> getToken(@Validated @RequestBody LoginParam loginParam) {
		YsUser ysUser = authService.wxappLogin(loginParam);
		String token = JwtToken.makeToken(ysUser.getId());
		//保存token到redis
		authService.saveToken(token, ysUser);
		String expiresTimeStr = JwtToken.getExpireTime(token);
		// 返回 token
		Map<String, Object> map = new LinkedHashMap<>(2);
		map.put("token", token);
		map.put("expires_time", expiresTimeStr);
		return AjaxResult.success(map).setMsg("登陆成功");
	}

	/**
	 * 获取用户信息
	 */
	@GetMapping("/userInfo")
	@ApiOperation(value = "获取用户信息", notes = "获取用户信息")
	@AuthCheck
	public AjaxResult<YsUser> getUserInfo() {
		Long uid = JwtToken.getUidByToken();
		YsUser ysUser=ysUserService.getById(uid);
		ysUser.setCouponSize(10);
		// 返回 token
		return AjaxResult.success(ysUser);
	}

	/***
	 * 更新用户头像和昵称信息
	 * @param person
	 * @return
	 */
	@PostMapping("/upinfo")
	@AuthCheck
	public AjaxResult upinfo(@RequestBody Map<String, String> person) {
		Long uid = JwtToken.getUidByToken();
		YsUser ysUser =ysUserService.getById(uid);
		ysUser.setNickname(person.get("nickName"));
		ysUser.setHeadpic(person.get("avatarUrl"));
		ysUserService.updateById(ysUser);
		return AjaxResult.success(ysUser);
	}

	/***
	 * 验证用户token是否过期
	 * @param token
	 * @return
	 */
	@GetMapping("/verify_token")
	public AjaxResult verifyToken(String token) {
		String expiresTimeStr = JwtToken.getExpireTime(token);
		DateTime date = DateUtil.parse(expiresTimeStr,DatePattern.NORM_DATETIME_FORMAT);
		if(System.currentTimeMillis()>date.getTime()){
			return AjaxResult.error("Token超时");
		}
		return AjaxResult.success();
	}

}
